<template>
	<view style="height: 100vh;width: 100vw;">
		<up-popup :show="deviceConfig.showPopup" mode="center" :closeOnClickOverlay="false" :round="20"
			bgColor="transparent" @close="close_device_popup">
			<view class="f-dc" v-if="deviceConfig.showPopup"
				style="width: 80vw;max-height: 70vh;min-height: 400px;background-color: #fff;border-radius: 20px;">
				<view class="x-c" style="padding: 20px;">
					<view class="x-f">
						<u-icon name="arrow-leftward" color="#333" size="24" @click="close_device_popup"></u-icon>

						<text style="margin-left: 4px;font-size: 12px;" v-if="deviceConfig.setName">返回</text>
					</view>
					<view class="x-c" style="flex: 1;">
						<text v-if="!deviceConfig.setName"
							style="font-size: 18px;">{{deviceConfig.tempDeviceInfo.aliasName || deviceConfig.tempDeviceInfo.name}}</text>
						<text v-else style="font-size: 18px;">设置别名</text>

					</view>
					<view class="x-ec">
						<template v-if="!deviceConfig.setName">
							<m-bubble type="list" :selectData="deviceConfig.formMenus" position="right"
								boxPosition="none" topOpsotion="right" bgcRgba="#fff" color="#333"
								@selectFun="deviceConfig_popup_menu">
								<u-icon name="list-dot" color="#333" size="28"></u-icon>
							</m-bubble>
						</template>
					</view>

				</view>

				<template v-if="!deviceConfig.setName">


					<!-- 蓝牙设备 -->
					<template v-if="deviceConfig.tempDeviceInfo.config.Communication == 'Bluetooth'">

						<template v-if="deviceConfig.bluetoothType">

							<view class="flex-auto f-dc" style="padding: 0 20px;font-size: 14px;">
								<view style="padding: 10px 0;">
									<text
										style="font-size: 20px;color: #000;font-weight: 600;">{{deviceConfig.tempDeviceInfo.config.MeasureName}}</text>
								</view>

								<view style="padding: 10px 0;">
									<text>{{deviceConfig.tempDeviceInfo.config.MeasureSpec}}</text>
									<text style="margin: 0 2px;">·</text>
									<text :style="{
								color: deviceConfig.tempDeviceInfo.connected ? '#05bc4f' : '#999'
								}">{{deviceConfig.tempDeviceInfo.connected ? '已连接' : '未连接'}}</text>
								</view>

								<view class="x-f" style="padding: 10px 0;">
									<view>
										<text>设备类型：</text>
									</view>

									<view>
										<text>{{deviceConfig.tempDeviceInfo.config.Communication}}</text>
									</view>
								</view>

								<view class="x-f" style="padding: 10px 0;">
									<view>
										<text>信号强度：</text>
									</view>

									<view>
										<template v-if="deviceConfig.showLoading">
											<text>正在扫描设备...</text>
										</template>

										<template v-else>
											<volume v-if="deviceConfig.findDevice" :num="deviceConfig.RSSI"></volume>

											<template v-else>
												<text>请确认设备蓝牙是否开启</text>
											</template>
										</template>
									</view>
								</view>

							</view>


							<view class="x-c" style="padding: 20px;">
								<button style="width: 90%;" @click="handlerClickByLink"
									:loading="deviceConfig.showLoading" :disabled="deviceConfig.showLoading"
									type="primary">{{deviceConfig.tempDeviceInfo.connected ? "断开连接" 
								: !deviceConfig.findDevice ?"刷新" 
								: deviceConfig.showLoading ? "扫描中" 
								: "连接设备"}}</button>
							</view>
						</template>

						<u-empty v-else text="开启蓝牙,以便查找附近蓝牙设备" iconSize="150" icon="/static/tabbar-icons/Bluetooth.png"
							style="height: 100%;">
							<u-button @click="openBluetoothAdapter" size="small" type="primary"
								:style="{marginTop:10+'px'} " text="立即开启"></u-button>
						</u-empty>
					</template>

				</template>

				<template v-else>
					<view class="flex-auto" style="padding: 0 20px;font-size: 14px;">
						<u-input placeholder="请输入别名" border="bottom" inputAlign="center" :focus="true"
							v-model="deviceConfig.changeName" suffixIcon="edit-pen-fill"></u-input>
					</view>


					<view class="x-ac" style="padding: 20px;">
						<button style="flex: 1;margin: 0 10px;" @click="handlerSetDeviceName(0)" type="primary"
							plain="">重置别名</button>
						<button style="flex: 1;margin: 0 10px;" @click="handlerSetDeviceName(1)"
							type="primary">设置别名</button>
					</view>
				</template>
			</view>
		</up-popup>
	</view>
</template>

<script setup lang="ts">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();
	import volume from "@/st_qms/components/page_index/signal";


	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1] as any;
	const eventChannel = currentPage.getOpenerEventChannel()

	let deviceConfig = reactive<any>({
		showPopup: true,
		formMenus: [{
			name: '取消配对',
			value: '',
			icon: 'close-circle',
			show: true,
		}, {
			name: '设置别名',
			value: '',
			icon: 'setting',
			show: true,
		},],
		setName: false,
		changeName: "",
		tempDeviceInfo: {},
		bluetoothType: false, // 蓝牙适配器是否开启
		RSSI: 0,


		findDevice: false, // 是否查询到设备
		showLoading: false,
		scanTimer: null
	});

	let choiceDeviceId = ref<any>(null);

	const getConnectedDevices = computed(() => {
		console.log(choiceDeviceId.value);
		console.log(bluetoothStore.connectedDevices);
		if (choiceDeviceId.value) {
			return bluetoothStore.connectedDevices[choiceDeviceId.value]
		} else {
			return []
		}
	})


	// 获取存储的蓝牙状态
	const adapterState = computed(() => {
		return bluetoothStore.adapterState.available
	});

	watch(adapterState, (nval : any, oval : any) => {
		console.log(nval);
		console.log(oval);
	})


	// 关闭按钮
	const close_device_popup = () => {
		if (deviceConfig.setName) {
			deviceConfig.setName = false;
			deviceConfig.changeName = "";
			return;
		};
		// 停止扫描和计时器
		if (deviceConfig.scanTimer) {
			clearInterval(deviceConfig.scanTimer);
			deviceConfig.scanTimer = null;
		};
		stopScan();
		uni.navigateBack({
			delta: 1,
			success() {
				eventChannel.emit("cancel", "back");
			}
		})
	};

	// 气泡下拉选中
	const deviceConfig_popup_menu = (data : any) => {
		switch (data.name) {
			case "取消配对":
				// 1、断开连接
				uni.$utils.$bluetooth.disconnectDevice(deviceConfig.tempDeviceInfo.deviceId);

				const deviceInfo = uni.$utils.deepClone(bluetoothStore.connectedDevices);
				// 2、删除设备信息
				Object.keys(deviceInfo).forEach(item => {
					delete deviceInfo[this.deviceConfig.tempDeviceInfo.deviceId]
				});
				bluetoothStore.connectedDevices = deviceInfo;

				// 关闭弹层
				close_device_popup();

				break;

			case "设置别名":

				deviceConfig.setName = true;
				deviceConfig.changeName = deviceConfig.tempDeviceInfo.aliasName ?
					deviceConfig.tempDeviceInfo.aliasName : deviceConfig.tempDeviceInfo.name;


				break;
			default:
				break;
		}
	};


	// 点击按钮搜索并连接
	const handlerClickByLink = () => {
		const _deviceType = deviceConfig.tempDeviceInfo.connected;
		switch (_deviceType) {
			case true:
				uni.showLoading({
					title: "正在断开"
				})
				// 断开设备
				uni.$utils.$bluetooth.disconnectDevice(deviceConfig.tempDeviceInfo.deviceId, () => {
					uni.hideLoading();
					// 重新设置蓝牙状态
					deviceConfig.tempDeviceInfo.connected = false;
					// 开启扫描
					startScan();
				});

				break;
			case false:
				// 判断是否查询到设备
				if (deviceConfig.findDevice) {
					// 连接设备
					uni.showLoading({
						title: "正在连接"
					})
					console.log(deviceConfig.tempDeviceInfo);
					uni.$utils.$bluetooth.connectDevice(deviceConfig.tempDeviceInfo, deviceConfig.tempDeviceInfo.config, () => {
						uni.hideLoading();

						deviceConfig.showLoading = false;
						deviceConfig.tempDeviceInfo.connected = true;


						if (deviceConfig.scanTimer) {
							clearInterval(deviceConfig.scanTimer);
						}
						stopScan();

					});

				} else {
					// 连接设备
					uni.showLoading({
						title: "正在扫描"
					})
					// 未查询到，刷新重试
					initBluetoothInfo();

				}

				break;
			default:
				break;
		}
	};

	// 开启蓝牙
	const openBluetoothAdapter = () => {
		switch (sysDeviceInfo.platform) {
			case "android":
				const BluetoothAdapter = plus.android.importClass(
					'android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类
				const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法
				console.log(blueadapter);
				if (blueadapter) {
					setTimeout(() => {
						// 判断蓝牙是否开启
						if (blueadapter.isEnabled()) {
							console.log('开启')

						} else {
							// 尝试开启蓝牙（Android原生方法）
							const isOpened = blueadapter.enable(); // 返回boolean，true表示开启成功（部分设备可能需要用户确认）
							console.log('开启结果：', isOpened);
						}
					}, 50)
				}
				break;
			case "ios":
				break;
			default:
				break;
		}
	}

	// 别名设置
	const handlerSetDeviceName = (str : any) => {
		let _title = str == 1 ? "是否确认设置" : "是否确认重置"
		uni.$utils.layer.confirm(_title, (ret : any) => {
			const {
				action
			} = ret;
			console.log(action);

			if (action == "confirm") {
				let lastName = ""
				if (str == 1) {
					lastName = deviceConfig.changeName
				} else {
					lastName = deviceConfig.tempDeviceInfo.name
				}

				uni.$utils.$bluetooth.setDeviceAlias(deviceConfig.tempDeviceInfo.deviceId, lastName);

			}
			deviceConfig.setName = false;
			deviceConfig.changeName = "";

			eventChannel.emit("setName");
		})
	};

	const initBluetoothInfo = async () => {
		try {

			deviceConfig.bluetoothType = true;
			const linkType = await uni.$utils.$bluetooth.isConnected(deviceConfig.tempDeviceInfo.deviceId);
			console.log(linkType);
			if (!linkType) { // 未连接
				// 开启扫描
				deviceConfig.findDevice = true;
				deviceConfig.showLoading = true;
				startScan();
			} else {
				deviceConfig.showLoading = false;
			}

		} catch (error : any) {
			if (error.code == "10001") {
				deviceConfig.bluetoothType = false;
			}
		}
	};

	const startScan = () => {
		// 清除可能存在的旧计时器，避免重复计时
		if (deviceConfig.scanTimer) {
			clearInterval(deviceConfig.scanTimer);
			deviceConfig.scanTimer = null;
		};

		// 重置扫描状态
		deviceConfig.showLoading = true; // 显示加载中
		deviceConfig.findDevice = false; // 标记是否在本轮5秒内找到设备
		let _currentSecond = 0; // 当前计时秒数
		// 启动蓝牙扫描
		console.log(deviceConfig.tempDeviceInfo.deviceId);
		uni.$utils.$bluetooth.startDiscovery((devices : any) => {
			// 过滤出目标设备（根据设备ID匹配）

			const targetDevice = devices.find(
				item => item.deviceId === deviceConfig.tempDeviceInfo.deviceId
			);


			if (targetDevice) {
				// 找到设备：更新信号强度，标记本轮已找到
				deviceConfig.RSSI = targetDevice.RSSI;
				deviceConfig.findDevice = true; // 关键：标记本轮找到设备
				deviceConfig.showLoading = false; // 隐藏加载中
			}
		});

		// 启动5秒计时器（每秒检查一次）
		deviceConfig.scanTimer = setInterval(() => {
			_currentSecond++; // 每秒累加
			console.log(_currentSecond);
			// 当计时达到5秒时
			if (_currentSecond >= 5) {
				if (deviceConfig.findDevice) {
					// 情况1：本轮5秒内找到设备 → 重置计时，进入下一轮5秒
					uni.hideLoading();
					_currentSecond = 0; // 重置秒数
					deviceConfig.findDevice = false; // 重置标记（等待下一轮判断）
					console.log("找到设备，进入下一轮5秒扫描");
				} else {
					uni.hideLoading();
					// 情况2：本轮5秒内未找到设备 → 停止扫描
					clearInterval(deviceConfig.scanTimer); // 清除计时器
					deviceConfig.scanTimer = null;
					deviceConfig.showLoading = false; // 隐藏加载中
					deviceConfig.findDevice = false; // 标记未找到
					stopScan(); // 停止蓝牙扫描
					console.log("5秒未找到设备，已停止扫描");
				}
			}
		}, 1000); // 每秒执行一次检查

	}
	const stopScan = () => {
		uni.$utils.$bluetooth.stopDiscovery();
	}

	onLoad(async (option) => {
		console.log(option);
		choiceDeviceId.value = option.deviceId;

		console.log(getConnectedDevices.value);

		deviceConfig.tempDeviceInfo = getConnectedDevices.value;

		// 强制初始化蓝牙信息
		const initBackInfo = await uni.$utils.$bluetooth.openBluetooth();
		if (initBackInfo.status == 0) {
			// 初始化蓝牙
			initBluetoothInfo();
		} else {

			deviceConfig.bluetoothType = false;
		}
	})

	onUnload(() => {
		clearInterval(deviceConfig.scanTimer);
		stopScan();
	})
</script>


<style lang="scss">
	page {
		background: transparent;
		height: 100vh;
	}
</style>